package com.ls.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * 解析jwt的token
 * 集成这个 ResourceServerConfigurerAdapter
 */
@Configuration
public class ResourceConfig extends ResourceServerConfigurerAdapter {


    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    /**
     * 转换jwt
     *
     * @return
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        // 需要一个sign签名 这叫对称加密
        jwtAccessTokenConverter.setSigningKey("ls");
        // 非对称加密的解密
//        ClassPathResource resource = new ClassPathResource("publicKey.txt");
//        String publicKey = null;
//        try {
//            // 都成string字符串
//            publicKey = FileUtil.readString(resource.getFile(), Charset.defaultCharset());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        // 设置到转换器里面
//        jwtAccessTokenConverter.setVerifierKey(publicKey);
        return jwtAccessTokenConverter;
    }

    /**
     * 让资源服务器 从tokenStore里面拿到token
     *
     * @param resources
     * @throws Exception
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore());
    }

    /**
     * 配置放行的路径
     * /swagger-ui/index.html
     *
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 关闭session
        http.sessionManagement().disable();
        // 关闭跨站请求伪造
        http.csrf().disable();
        http.authorizeRequests().antMatchers(
                "/swagger-resources/configuration/ui",  //用来获取支持的动作
                "/swagger-resources",                   //用来获取api-docs的URI
                "/swagger-resources/configuration/security",//安全选项
                "/webjars/**",
                "/swagger-ui/**",
                "/druid/**",
                "/actuator/**"
        ).permitAll();
        http.authorizeRequests().anyRequest().authenticated();
        http.headers().cacheControl();
    }
}